//
//  imprintApp.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/23.
//

import SwiftUI
import UMCommon
import UMPush

#if DEBUG
let isDebug = true
#else
let isDebug = false
#endif

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        AppInitializer.initialize(delegate: self)
        // 设置通知中心的代理
        UNUserNotificationCenter.current().delegate = self
        // 打印所有注册的 URL Schemes
        if let urlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [[String: Any]] {
            for urlType in urlTypes {
                if let schemes = urlType["CFBundleURLSchemes"] as? [String] {
                    showLog("Registered URL Schemes: \(schemes)")
                }
            }
        }
        return true
    }
    func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
        showLog("log-DidReceiveMemoryWarning")
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        //旧版本的QQ授权回调
        let handled = TencentOAuth.handleOpen(url)
        return handled
    }
    
    //    // 接收友盟通知,后台推送，需要配置 content-available = 1，会导致有时候接受不了，取消这个
    //     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    //         UMessage.didReceiveRemoteNotification(userInfo)
    //         showLog("接收友盟通知")
    //     }
    
    // 获取友盟 DeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UMessage.registerDeviceToken(deviceToken)
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        showLog("Device Token: \(token)")
    }
    
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
              let url = userActivity.webpageURL else { return }
        
        // 处理 Universal Link 回调（新版推荐方式）
        let handled = TencentOAuth.handleUniversalLink(url)
        showLog("Universal Link 处理结果: \(handled)")
    }
}


@main
struct imprintApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @StateObject var mainViewModel = MainViewModel()

    
    var body: some Scene {
        WindowGroup {
            WelcomeView()
                .environmentObject(themeManager) // 只需在这里注入一次
                .environmentObject(pathManager)
                .environmentObject(userManager)
                .environmentObject(commonManager)
                .environmentObject(aiRoleManager)
                .environmentObject(mainViewModel)
                .environmentObject(backgroundManager)
                .environmentObject(BackupsManager.shared)
                .environmentObject(AppStorageManager.shared)
                .onOpenURL { url in
                    //处理QQ回调
                    let handled = TencentOAuth.handleOpen(url)
                    if !handled {
                        TencentOAuth.handleUniversalLink(url)
                        showLog("QQ登陆UniversalLink模式: \(handled)")
                    } else {
                        showLog("QQ登陆Scheme模式: \(handled)")
                    }
                    // 处理微信回调
                     WXApi.handleOpen(url, delegate: SceneWxDelegate())
                }
                .onAppear {
                    // 添加通知观察者
                    NotificationCenter.default.addObserver(
                        forName: UIApplication.willEnterForegroundNotification,
                        object: nil,
                        queue: .main
                    ) { _ in
                        showLog("应用从后台切换到前台")
                        NotificationCenter.default.post(name: .background, object: false)
                        commonManager.isBackground = false
                    }
                    
                    NotificationCenter.default.addObserver(
                        forName: UIApplication.didEnterBackgroundNotification,
                        object: nil,
                        queue: .main
                    ) { _ in
                        showLog("应用进入后台")
                        NotificationCenter.default.post(name: .background, object: true)
                        commonManager.isBackground = true
                    }
                }
                .onDisappear {
                    // 移除通知观察者
                    NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
                    NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
                }
        }
    }
}

// 共享的预览环境配置函数
func configurePreviewEnvironment<Content: View>(for view: Content) -> some View where Content: View {
    //预览也要注入ThemeManager，不然报错
    let pathManager = PathManager()
    let mainViewModel = MainViewModel()
    return view.environmentObject(themeManager)
        .environmentObject(pathManager)
        .environmentObject(userManager)
        .environmentObject(commonManager)
        .environmentObject(aiRoleManager)
        .environmentObject(mainViewModel)
        .environmentObject(backgroundManager)
        .environmentObject(BackupsManager.shared)
        .environmentObject(AppStorageManager.shared)
}
